package com.anji.plus.gaea.archiver.config;

import com.anji.plus.gaea.archiver.service.ArchiverService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.config.TriggerTask;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.util.StringUtils;

import java.net.InetAddress;
import java.util.Date;
/**
 * springboot自动装配类
 *
 * @author 木子李·De
 * @since 2021/2/3 14:16
 */
@Configuration
@EnableScheduling
@EnableConfigurationProperties(ArchiverProperties.class)
@ComponentScan("com.anji.plus.gaea.archiver")
//@ConditionalOnGaeaComponent(ArchiverProperties.COMPONENT_NAME)
@ConditionalOnProperty(name= ArchiverProperties.COMPONENT_PREFIX + ArchiverProperties.COMPONENT_NAME + ".enabled", havingValue="true")
public class AutoConfiguration implements SchedulingConfigurer {
    private static Logger logger = LoggerFactory.getLogger(AutoConfiguration.class);

    @Autowired
    private ArchiverProperties archiverProperties;

    @Autowired
    private ArchiverService archiverService;

    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        if (archiverProperties.getArchiveScheduledCron() != null && !StringUtils.isEmpty(archiverProperties.getExecuteIp())) {
            //限制pi
            try {
                InetAddress addr = InetAddress.getLocalHost();
                String localIp = addr.getHostAddress();
                logger.info("Scheduled Task. localIp:{}, executeIp：{}", localIp, archiverProperties.getExecuteIp());
                if(!archiverProperties.getExecuteIp().equals(localIp)) {
                    logger.info("No need to execute scheduled...");
                    return;
                }
            } catch (Exception e) {
                logger.error(e.getMessage());
                return;
            }
        }
        scheduledTaskRegistrar.addTriggerTask(new TriggerTask(() -> archiverService.doArchiveTable(), triggerContext -> {
            // 定义定时器的Cron间隔，默认每月2号，凌晨3:0:0执行归档
            String cron = "0 0 3 2 */1 ?";
            if(archiverProperties.getArchiveScheduledCron() != null && archiverProperties.getArchiveScheduledCron().trim().length() > 5){
                cron = archiverProperties.getArchiveScheduledCron().trim();
            }
            //调用执行器
            return new CronTrigger(cron).nextExecutionTime(triggerContext);
        }));
    }
}
